package com.example.onlineeducation.ui.offline

import android.content.Context
import android.content.Intent
import android.util.Log
import android.view.View
import androidx.core.view.isVisible
import com.baidu.location.BDLocation
import com.example.onlineeducation.App
import com.example.onlineeducation.BuildConfig
import com.example.onlineeducation.R
import com.example.onlineeducation.base.BaseActivity
import com.example.onlineeducation.data.constant.OfflineStudyLiveState
import com.example.onlineeducation.data.entity.OfflineStudyLiveListEntity
import com.example.onlineeducation.data.entity.OfflineStudyReplaceSignListEntity
import com.example.onlineeducation.databinding.OfflineStudyDetailAcBinding
import com.example.onlineeducation.databinding.OfflineStudyListItemBinding
import com.example.onlineeducation.databinding.OfflineStudySignBehalfActivityBinding
import com.example.onlineeducation.databinding.OfflineStudySignBehalfItemBinding
import com.example.onlineeducation.ui.auth.LoginConfirmActivity
import com.example.onlineeducation.viewmodel.LoginVM
import com.example.onlineeducation.viewmodel.OfflineStudySignBehalfVM
import com.example.onlineeducation.widget.SignBehalfDialog
import com.example.onlineeducation.widget.SignBehalfPictureDialog
import com.yc.jetpacklib.extension.*
import com.yc.jetpacklib.net.doSuccess
import com.yc.jetpacklib.recycleView.YcDecoration
import com.yc.jetpacklib.recycleView.YcRecyclerViewAdapter
import com.yc.jetpacklib.refresh.YcRefreshSpecialUtil
import com.yc.jetpacklib.release.YcSpecialViewSmart
import com.yc.jetpacklib.utils.YcRegularUtil
import com.yc.jetpacklib.utils.YcRegularUtil.ycRegular
import com.yc.jetpacklib.utils.YcResources
import com.yc.jetpacklib.utils.ycDp

/**
 * Creator:
 * Date: 2022/4/1 15:10
 * UseDes:线下学习列表的活动详情
 */
class OfflineStudySignBehalfActivity :
    BaseActivity<OfflineStudySignBehalfActivityBinding>(OfflineStudySignBehalfActivityBinding::inflate) {
    companion object {
        private const val KEY_ACTIVE_INFO_ID = "key_active_info_id"
        private const val KEY_STUDY_STATE = "key_study_state"

        @JvmStatic
        fun newInstance(context: Context, activeInfoId: String, studyState: Int) {
            context.startActivity(
                Intent(context, OfflineStudySignBehalfActivity::class.java).apply {
                    putExtra(KEY_ACTIVE_INFO_ID, activeInfoId)
                    putExtra(KEY_STUDY_STATE, studyState)
                })
        }
    }

    private val mAdapter by YcRecyclerViewAdapter.ycLazyInitApply<OfflineStudyReplaceSignListEntity, OfflineStudySignBehalfItemBinding>(
        OfflineStudySignBehalfItemBinding::inflate
    ) {
        mOnUpdate = { mOfflineStudyReplaceSignListEntity ->
            ivStudy.ycLoadImageNet(mOfflineStudyReplaceSignListEntity.faceUrl, errorImg = R.drawable.ic_topic)
            tvStudyName.text = mOfflineStudyReplaceSignListEntity.userName
            tvSignInTime.text = "代签到时间:"+mOfflineStudyReplaceSignListEntity.signInTime
            tvSignOutTime.text = "代签退时间:"+mOfflineStudyReplaceSignListEntity.signOutTime
            tvReplaceReason.text = mOfflineStudyReplaceSignListEntity.replaceRemark
//            tvSignOut.visibility = if (mOfflineStudyReplaceSignListEntity.signOutTime.equals("-")) {
//                View.VISIBLE
//            } else {
//                View.GONE
//            }
            tvSignOut.setOnClickListener {
                mSignOutDialog.setOkOnClick {
                    if (mSignOutDialog.isEmpty().ycIsEmpty()) {
                        signOutPersonId = mOfflineStudyReplaceSignListEntity.rePersonId
                        mViewModel.uploadFile(mSignOutDialog.getUploadEntity(), false)
                    } else {
                        showToast(mSignOutDialog.isEmpty())
                    }
                }.show()

            }
        }
    }
    private var signOutPersonId = ""
    private lateinit var mRefreshUtil: YcRefreshSpecialUtil
    private val mViewModel: OfflineStudySignBehalfVM by ycViewModels()
    private val mInsertDialog by lazy {
        SignBehalfDialog(this@OfflineStudySignBehalfActivity, this@OfflineStudySignBehalfActivity)
    }
    private val mSignOutDialog by lazy {
        SignBehalfPictureDialog(
            this@OfflineStudySignBehalfActivity,
            this@OfflineStudySignBehalfActivity
        )
    }
    private var mBDLocation: BDLocation? = null
    private lateinit var mActiveInfoId: String
    private var mStudyState: Int = OfflineStudyLiveState.ERROR//学习活动状态
    override fun OfflineStudySignBehalfActivityBinding.initView() {
        actionBar.setTitle("代签到")
        intent.apply {
            mActiveInfoId = getStringExtra(KEY_ACTIVE_INFO_ID)!!
            mStudyState = getIntExtra(KEY_STUDY_STATE, OfflineStudyLiveState.ERROR)
        }
        App.mInstant.mBaiduLocationVM.start()
        App.mInstant.mBaiduLocationVM.mBDLocation.observe {
            mBDLocation = it
        }
        rv.adapter = mAdapter
        rv.addItemDecoration(YcDecoration(1.ycDp()).apply {
            setLineColor(YcResources.getColorRes(R.color.every_lib_line))
        })
        srl.setNoMoreData(true)
        mRefreshUtil = YcRefreshSpecialUtil(
            this@OfflineStudySignBehalfActivity,
            srl,
            mAdapter,
            YcSpecialViewSmart(rv, fl)
        ).apply {
            mRefreshAndLoadMore = { isRefresh: Boolean, pageIndex: Int, pageSize: Int ->
                if (isRefresh) {
                    mViewModel.getReplaceSignList(mActiveInfoId)
                }
            }
        }
        //只有在活动进行中，才可以新增人员（即代签到）
        btnInsert.isVisible = mStudyState == OfflineStudyLiveState.STUDY_LIVE_IN_PROGRESS
        btnInsert.setOnClickListener {
            mInsertDialog.setGetVerifyCodeClick {
                checkPhoneNum(mInsertDialog.getPhone()) {
                    mInsertDialog.resetStartTime()
                    mViewModel.sendVerifyCode(mInsertDialog.getPhone())
                }

            }.setOkOnClick {
                if (mInsertDialog.isEmpty().ycIsEmpty()) {
                    mViewModel.uploadFile(mInsertDialog.getUploadEntity().reSignInMedia, true)
                } else {
                    showToast(mInsertDialog.isEmpty())
                }
            }.show()
        }
        mViewModel.apply {
            mGetReplaceSignList.observe {
                it.doSuccess {
                    mAdapter.addAllData(it)
                }.ycShowNetError()
                mRefreshUtil.ycRefreshAndLoadMoreResult(it)
            }
            mSendVerifyCode.observe {
                it.doSuccess { showToast("验证码发送成功,请注意查收") }.ycShowNetError("发送验证码失败")
            }
            mUploadFileSignInResult.observe {
                it.doSuccess {
                    mViewModel.replaceSign(
                        mActiveInfoId,
                        mBDLocation?.addrStr.ycToNoEmpty(),
                        mBDLocation?.latitude.toString(),
                        mBDLocation?.longitude.toString(),
                        it?.mediaId.toString(),
                        mInsertDialog.getUploadEntity()
                    )
                }.ycShowNetError()
            }
            mViewModel.mUploadFileSignOutResult.observe {
                it.doSuccess { uploadFileResultJson ->
                    mViewModel.replaceSignOut(
                        mActiveInfoId,
                        mBDLocation?.addrStr.ycToNoEmpty(),
                        mBDLocation?.latitude.toString(),
                        mBDLocation?.longitude.toString(),
                        uploadFileResultJson?.mediaId.toString(),
                        signOutPersonId
                    )
                }.ycShowNetError()
            }
            mReplaceSign.observe {
                it.doSuccess {
                    showToast("代签成功!")
                    mInsertDialog.dismiss()
                    mRefreshUtil.startRefresh()
                }.ycShowNetError()
            }

            mReplaceOut.observe {
                it.doSuccess {
                    showToast("签退成功!")
                    mSignOutDialog.dismiss()
                    mRefreshUtil.startRefresh()
                }.ycShowNetError()
            }
        }

    }

    private inline fun checkPhoneNum(phoneNum: String, crossinline success: (() -> Unit)) {
        if (phoneNum.ycRegular(YcRegularUtil.PHONE)) {
            success.invoke()
        } else {
            showToast("请输入正确的手机号")
        }
    }

}